<?php

/*
 *   add a file to monitor
 */

include_once "file.php";
include_once "sql.php";
include_once "features.php";
include_once "get_item.php";
include_once "to_index.php";

header("Access-Control-Allow-Origin: *");

sqlInit();

if( ($f = get_img_file()) != false && isset($_REQUEST["token"]) ){
  $pgm = get_pgm($f);
  $thumb = get_thumb($f);
  $m = sqlQuery("SELECT MAX(`id`) FROM collections WHERE `token`='" . $_REQUEST["token"] . "'", array("MAX(`id`)"));
  if( $m[0]["MAX(`id`)"] == "" ) $id = 0;
  else $id = intval($m[0]["MAX(`id`)"]) + 1;
  sqlQuery("INSERT INTO collections VALUES ('" . $_REQUEST["token"] . "', UNHEX('" . bin2hex($pgm) . "'), UNHEX('" . bin2hex($thumb) . "') , " . $id . "); ");
}
if( isset($_REQUEST["token"]) ){
  $r = sqlQuery("SELECT HEX(`pgm`), `thumb`, `id` FROM collections WHERE token = '".$_REQUEST["token"]."'", array("HEX(`pgm`)","thumb","id"));
  foreach($r as $k => $v){
    unset( $r[$k]["HEX(`pgm`)"] );
    unset( $r[$k][0] );
    $r[$k]["elements"] = array();
    $l = search_by_pgm( pack("H*" , $v["HEX(`pgm`)"]) );
    $l = array_slice($l,0,5,true);
    foreach($l as $kk => $vv){
      $r[$k]["elements"][] = get_item($kk);
      $r[$k]["elements"][count($r[$k]["elements"])]["score"] = $vv;
    }
  }
  echo json_encode($r);
}

sqlClose();

?>
